<?php

class Modules_News extends Module {

	public $name = 'news';
	public $title = "Новости";

	public function actions() {
		return array(
			'news' => "Показать новости",
			'rss' => "Показать RSS",
		);
	}

	public function mainActions() {
		return array(
			'news' => "Показать новости",
			'rss' => "Показать RSS",
		);
	}

	protected function _actionproperties(Blocks  $block) {
		switch ($block->action) {
			case "news":
				return $this->_News_actionproperties($block);
				break;

			case "rss":
				return $this->_Rss_actionproperties($block);
				break;

			default :
				return "Нет";
				break;
		}
	}

	public static function subMenu() {
		return array(
			array(
				'url' => '/admin.php?module=news&action=categories',
				'title' => 'Категории новостей',
				'icon' => '/tpl/admin/images/list.png',
			),
			array(
				'url' => '/admin.php?module=news&action=news_create',
				'title' => 'Добавить новость',
				'icon' => '/tpl/admin/images/add_item.png',
			),
		);
	}

	public function adminActionIndex() {
		Request::redirect("?module=news&action=categories");
	}

	public function adminActionCategories() {
		$this->access("r");

		App::registerCoreScript("jquery");

		$cats = Doctrine_Query::create()
						->from("NewsCategories")
						->execute();
		$this->tpl()->assign(array(
			'cats' => $cats,
		));
		return $this->tpl()->fetch('cats_list.html');
	}

	public function adminActionCat_delete() {
		$this->access("d");

		$cat = $this->_load_cat();
		$cat->delete();

		Request::redirect("?module=news&action=categories");
	}

	public function adminActionCat_save() {
		$this->access("c");

		$catData = isset($_REQUEST['cat']) ? $_REQUEST['cat'] : array();
		$catData['id'] = (int) $catData['id'];

		$cat = $catData['id'] ? NewsCategoriesTable::getInstance()->find($catData['id']) : new NewsCategories();
		$cat->fromArray($catData);
		$cat->save();

		if (Admin::$XMLHttpRequest) {
			return json_encode($cat->toArray());
		}

		Request::redirect("?module=news&action=categories");
	}

	public function adminActionNews() {
		$this->access("r");

		$cat = !empty($_REQUEST['cat']) ? (int) $_REQUEST['cat'] : 0;
		$cat = Doctrine_Query::create()
						->from('NewsCategories c')
						//->leftJoin("c.News")
						->where("c.id = ?", $cat)
						->fetchOne();

		if (!$cat) Request::redirect(404);

		$this->tpl()->assign(array(
			'cat' => $cat,
			'news' => $cat->News,
		));

		return $this->tpl()->fetch('news_list.html');
	}

	public function adminActionNews_create() {
		$this->access("c");

		$new = new News();
		$new->date_publish = time();

		return $this->_news_edit($new, 'news_create.html');
	}

	public function adminActionNews_edit() {
		$this->access("c");

		$new = $this->_load_new();

		$new->text = !empty($new->text) ? ($new->preview . '<!-- pagebreak -->' . $new->text) : $new->preview;

		return $this->_news_edit($new, 'news_edit.html');
	}

	public function adminActionNews_active() {
		$this->access("p");

		$new = $this->_load_new();
		$new->active = 1;
		$new->save();

		Request::redirect("?module=news&action=news&cat={$new->category}");
	}

	public function adminActionNews_unactive() {
		$this->access("p");

		$new = $this->_load_new();
		$new->active = 0;
		$new->save();

		Request::redirect("?module=news&action=news&cat={$new->category}");
	}

	public function adminActionNews_delete() {
		$this->access("d");

		$new = $this->_load_new();
		$new->delete();

		Request::redirect("?module=news&action=news&cat={$new->category}");
	}

	public function adminActionNews_save() {
		$this->access("c");

		$newData = isset($_REQUEST['new']) ? $_REQUEST['new'] : array();
		$newData['id'] = (int) $newData['id'];

		$text = explode('<!-- pagebreak -->', $newData['text']);
		$newData['date_publish'] = strtotime($newData['date_publish']);
		$newData['preview'] = $text[0];
		$newData['text'] = isset($text[1]) ? $text[1] : "";
		

		$new = !$newData['id'] ? new News() : NewsTable::getInstance()->find($newData['id']);
		$new->fromArray($newData);

		if ($new->id && !empty($newData['del_img'])) {
			$new->img_ext = null;

			$dr = DIRECTORY_SEPARATOR;

			/* Большое изображение */
			$filename = RP . "files{$dr}news{$dr}{$new->id}.{$new->img_ext}";
			if (file_exists($filename) && is_writable($filename)) unlink($filename);

			/* Малое изображение */
			$filename = RP . "files{$dr}news{$dr}tumb_{$new->id}.{$new->img_ext}";
			if (file_exists($filename) && is_writable($filename)) unlink($filename);
		}

		if (empty($_FILES['new_img']['error'])) {
			$img = Image::create($_FILES['new_img']['tmp_name']);
			$ext = strtolower($img->getFormat());

			$new->img_ext = $ext;
			if (!$new->id) $new->save();
			$this->chekImgDir();

			$dr = DIRECTORY_SEPARATOR;

			/* Большое изображение */
			$filename = RP . "files{$dr}news{$dr}{$new->id}.$ext";
			$img->resize(500, 1000);
			$img->save($filename);

			/* Малое изображение */
			$filename = RP . "files{$dr}news{$dr}tumb_{$new->id}.$ext";
			$img->resize(150, 150);
			$img->save($filename);
		}

		$new->save();

		Request::redirect(isset($_REQUEST['apply']) ? ('?module=news&action=news_edit&id=' . $new->id) : ('?module=news&action=news&cat=' . $new->category));
	}

	public function actionNews() {
		$id = !Request::empty_('id') ? (int) Request::get('id') : 0;
		if ($id && $this->block->field == 0) {
			return $this->_showNew($id);
		} else {
			return $this->_showNews();
		}
	}

	private function _showNew($id) {
		$new = Doctrine_Query::create()
						->from("News n")
						->leftJoin("n.Category")
						->where('n.id = ?', $id)
						->fetchOne();

		if (!$new) Request::redirect(404);

		$tpl = $this->getTpl('new.html');

		$this->tpl()->assign(array(
			'new' => $new,
		));
		return $this->tpl()->fetch($tpl);
	}

	private function _showNews() {
		$cat = $this->block->property('category')->value;
		$count = $this->block->property('count')->value;
		$tpl = $this->getTpl('news.html');

		if (empty($count)) $count = 10;

		if ($cat) {
			$news = Doctrine_Query::create()
							->from('News n')
							->leftJoin('n.Category')
							->where('n.category = ?', $cat)
							->orderBy('n.date_publish')
							->limit($count)
							->offset(0)
							->execute();
		} else {
			$news = Doctrine_Query::create()
							->from('News n')
							->leftJoin('n.Category')
							->orderBy('n.date_publish')
							->limit($count)
							->offset(0)
							->execute();
		}

		$this->tpl()->assign(array(
			'news' => $news,
			'block' => $this->block,
		));
		return $this->tpl()->fetch($tpl);
	}

	private function _load_cat() {
		$id = !empty($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
		if (!$id) Request::redirect(404);
		$cat = NewsCategoriesTable::getInstance()->find($id);
		if (!$cat) Request::redirect(404);

		return $cat;
	}

	private function _load_new() {
		$id = !empty($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
		if (!$id) Request::redirect(404);
		$new = NewsTable::getInstance()->find($id);
		if (!$new) Request::redirect(404);

		return $new;
	}

	private function _news_edit($new, $tpl) {
		$cats = Doctrine_Query::create()
						->from('NewsCategories c')
						->execute();

		App::registerCoreScript('jquery');
		App::registerCoreScript('jquery-ui');
		App::registerCoreScript('tiny_mce');
		App::registerCoreScript('colorbox');
		App::registerCoreScript('base');
		App::registerScript('/js/tiny_mce_init.js');

		App::registerCoreStyle('colorbox');
		App::registerCoreStyle('jquery-ui');

		$this->tpl()->assign(array(
			'new' => $new,
			'cats' => $cats,
		));

		return $this->tpl()->fetch($tpl);
	}

	private function _News_actionproperties(Blocks $block) {
		$cats = NewsCategoriesTable::getInstance()->findAll();
		$tpls = $this->avaliableTemplatesList('news', $block);
		$pages = $this->avaliableLinkedPages($block);
		$currentPage = $block->field == 0 ? $block->page_id : false;

		$this->tpl()->assign(array(
			'cats' => $cats,
			'tpls' => $tpls,
			'block' => $block,
			'pages' => $pages,
			'currentPage' => $currentPage,
		));
		return $this->tpl()->fetch('_news_actionproperties.html');
	}

}